export const storage = {
  set(key, value) {
    api.setPrefs({ key, value });
  },

  get(key) {
    return api.getPrefs({ sync: true, key });
  },

  del(key) {
    api.removePrefs({ key });
  }
};

export const memory = {
  set(key, value) {
    api.setGlobalData({ key, value });
  },

  get(key) {
    return api.getGlobalData({ key });
  }
};
// 加密
export const sign = param => {
  return new Promise((resolve, reject) => {
    try {
      var signature = api.require("signature");
      param = param ? param : {};
      let str = "";
      var sorted_keys_array = Object.keys(param).sort();
      sorted_keys_array.map(key => {
        str += param[key];
      });
      signature.sha1(
        {
          data: str
        },
        function(res, error) {
          if (!error) {
            signature.md5(
              {
                data: `${res.value}LKJHHBBGHFGHFG`
              },
              function(ret, err) {
                if (ret.status) {
                  resolve(ret);
                } else {
                  reject(err);
                }
              }
            );
          } else {
            resolve({ value: "" });
          }
        }
      );
    } catch (error) {
      resolve({ value: "" });
    }
  });
};
// 提示
export const message = {
  toast: str => {
    api.toast({
      msg: str || "内部错误,请联系管理员!",
      duration: 2000,
      location: "bottom"
    });
  },
  alert: param => {
    window.MuseUIMessage.close();
    window.MuseUIMessage.alert(param.msg || "提示信息!", param.title || "", {
      type: param.type || "error",
      okLabel: "确认"
    }).then(({ result }) => {
      if (result) {
        param.callback && param.callback();
      }
    });
    // api.alert({
    //     title: "提示",
    //     msg: param.msg || "未知提示!",
    // }, function (ret, err) {
    //     param.callback && param.callback();
    // });
  }
};
// 总路由
export const router = {
  /**
   * @description 跳转页面
   * @author 一枚前端
   */
  to(path, param) {
    if (!path) path = "home";
    api.openWin({
      name: `${path}`,
      url: `${path}.html`,
      pageParam: param || {},
      overScrollMode: "scrolls"
    });
  },
  /**
   * @description 删除历史并且跳转页面
   * @author 一枚前端
   */
  replace(path, param) {
    if (!path) path = "home";
    var winNames = api.winName;
    api.execScript({
      name: "root",
      script: `toReplaces('${path}','${JSON.stringify(param || {})}')`
    });
    api.frames().map(val => {
      api.closeFrame({
        name: val.name
      });
    });
    api.closeToWin({
      name: "root"
    });
  }
};
// 原生下拉刷新
export const initRefreshHeader = ({ param = {}, callback }) => {
  // { param = {}, callback }
  console.log(JSON.stringify(param) + "--------");
  typeof callback === "function" ? callback() : ""; //初次运行一次
  api.setRefreshHeaderInfo(
    {
      visible: true,
      bgColor: param.bgColor || "#ffbb17",
      textColor: param.textColor || "#fff",
      textDown: "下拉刷新...",
      textUp: "松开刷新...",
      textLoading: "拼命请求中.."
      // showTime: true
    },
    (ret, err) => {
      if (typeof callback === "function") {
        callback()
          .then(res => {
            api.refreshHeaderLoadDone();
          })
          .catch(res => {
            api.refreshHeaderLoadDone();
          });
      }
    }
  );
};
// 时间操作相关
export const transformDate = {
  /**
   * @description 计算两个时间段内相差天数
   * @param {string} startDate 开始时间
   * @param {string} endDate 开始时间
   * @param {string} sign 计算方式
   * @returns {number} msg 结果
   * @author 一枚前端
   */
  countTime(startDate, endDate, sign) {
    sign = sign ? sign : "day";
    try {
      if (startDate && endDate) {
        var redata = "",
          startTime = new Date(startDate).getTime(),
          endTime = new Date(endDate).getTime();
        if (sign == "day") {
          // redata = Math.abs(Math.ceil(Math.floor((startTime - endTime) / 86400000)));
          redata = Math.abs(Math.ceil((startTime - endTime) / 86400000));
        }
        return redata;
      } else {
        throw new Error("开始和结束时间不能为空");
      }
    } catch (error) {
      console.error(error);
    }
  },
  /**
   * @description 获取当前时间为周几
   * @param {number} week 当前周的编号
   * @author 一枚前端
   */
  setWeek(week) {
    var str = "周";
    switch (week) {
      case 0:
        str += "日";
        break;
      case 1:
        str += "一";
        break;
      case 2:
        str += "二";
        break;
      case 3:
        str += "三";
        break;
      case 4:
        str += "四";
        break;
      case 5:
        str += "五";
        break;
      case 6:
        str += "六";
        break;
    }
    return str;
  }
};
// 工具类相关
export const tool = {
  /**
   * @description 函数节流
   * @param {function} fn 需要执行的函数
   * @param {number} delay 节流毫秒数 默认300毫秒
   * @author zengbao
   */
  throttleFun: (fn, delay) => {
    var timer = null;
    return function() {
      var context = this,
        args = arguments;
      clearTimeout(timer);
      timer = setTimeout(function() {
        fn.apply(context, args);
      }, delay || 300);
    };
  }
};
